package com.sanyue.tools;

import org.junit.Test;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author sanyue
 * @version 1.0
 * @description: TODO
 * @date 2022/2/3 下午12:44
 */
public class IsIpLegal {

    @Test
    public void testIpIsLegal() {
        while (true) {
            System.out.println("请输入要验证的IP地址：");
            Scanner scanner = new Scanner(System.in);
            String ipStr = scanner.next();
            System.out.println(isIpLegal(ipStr) == true ? "合法" : "不合法 ");
        }
    }
//    类 地址范围
//    A	  0.0.0.0 ~ 127.255.255.255
//    B	128.0.0.0 ~ 191.255.255.255
//    C	192.0.0.0 ~ 223.255.255.255
//    D	224.0.0.0 ~ 239.255.255.255
//    E	240.0.0.0 ~ 255.255.255.255
    public boolean isIpLegal(String ipStr) {
        //ip地址范围：(1~255).(0~255).(0~255).(0~255)
        String ipRegEx = "^([1-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))(\\.([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))){3}$";
        //String ipRegEx = "^([1-9]|([1-9]\\d)|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))(\\.(\\d|([1-9]\\d)|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))){3}$";
        //String ipRegEx = "^(([1-9]\\d?)|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))(\\.(0|([1-9]\\d?)|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))){3}$";
        Pattern pattern = Pattern.compile(ipRegEx);
        Matcher matcher = pattern.matcher(ipStr);
        if (matcher.matches()) {
            return true;
        } else {
            return false;
        }
    }
}
